package com.dongdongshop.mq;

import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.TbOrder;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

import java.util.Objects;

@RocketMQTransactionListener
public class MQTransactionCallback implements RocketMQLocalTransactionListener {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    //执行本地事务的方法
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        MessageHeaders headers = message.getHeaders();
        String msgId = headers.getId().toString();
        try{
            System.out.println("执行本地事务(修改订单状态)用到的参数:"+o);
            TbOrder order = (TbOrder) o;
            String tradeNoOut = order.getTradeNoOut();
            String tradeNo = order.getTradeNo();
            tbOrderMapper.updateOrderStatus(tradeNoOut,tradeNo);
            tbOrderItemMapper.updateOrderItem(tradeNoOut,tradeNo);
            String msg = new String((byte[]) message.getPayload());
            redisTemplate.boundValueOps("A:"+msgId).set("1");
            System.out.println("要发送的消息:"+msg);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            redisTemplate.boundValueOps("A:"+msgId).set("2");
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String msgId = message.getHeaders().getId().toString();
        String status = (String) redisTemplate.boundValueOps("A:" + msgId).get();
        if (Objects.equals(status,"2")){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
